import 'package:base_flutter/base_flutter.dart';
import 'package:image_picker/image_picker.dart';
import 'package:ls_work/config/permission_center_config.dart';
import 'package:ls_work/emergency_event/emergency_event_model.dart';
import 'package:ls_work/emergency_event/response/emergency_event_detail_data.dart';
import 'package:ls_work/emergency_event/response/emergency_event_type_data.dart';
import 'package:ls_work/login/page/user_manager.dart';
import 'package:ls_work/ui/select_employee_page.dart';
import 'package:ls_work/ui/select_old_page.dart';
import 'package:ls_work/viewmodel/model/combo_data_model.dart';
import 'package:saas_order_meal/model/combo_model.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:saas_order_meal/net/net_response/code_value_list.dart';

import '../../util/ext_utils.dart';
import '../../widgets/add_image_widget.dart';
class EditEmergencyEventViewModel extends BaseViewModel{

  dynamic id;

  EditEmergencyEventViewModel(super.context,{this.id}){
    detailData = EmergencyEventDetailData(firstHandler: UserManager.userName);
  }

  EmergencyEventDetailData? detailData;

  var model = EmergencyEventModel();
  
  var commonModel = ComboModel();

  Map<String, List<CodeValueList>> comboListMap = {};

  List<EmergencyEventTypeData> eventTypeList = [];

  var inEditMode = true;

  Future<void> initData() async {
    showLoadingState();
    try{
      if(id!=null){
        detailData =  await model.eventDetail(id);
      }
      await getComboData('10019');
      eventTypeList =  await model.emergencyEventType();
      showContent();
    }catch(e){
      showErrorState(e.toNetError());
    }
    
  }

  Future<void> getComboData(String code) async {
    comboListMap[code] = await commonModel.getComboData(code);
  }

  @override
  void onCreated() {
    super.onCreated();
    initData();
  }

  void chooseEventNature(){
    var current = (detailData?.eventNature.isNullOrEmpty()==true)?null:eventTypeList.firstWhere((e)=>e.codeValue==detailData?.eventNature);
    DataPickerView(context, eventTypeList,currentFirstData: current,onSubmitListener: (p1,p2,p3){
      var item = eventTypeList[p1];
      if(detailData?.eventNature!=item.codeValue){
        detailData?.eventNature = item.codeValue;
        detailData?.eventNatureName = item.name;
        detailData?.eventType = null;
        detailData?.eventTypeName = null;
        notifyListeners();
      }

    }).show();
  }

  void chooseEventType(){
    var currentNature = (detailData?.eventNature.isNullOrEmpty()==true)?null:eventTypeList.firstWhere((e)=>e.codeValue==detailData?.eventNature);
    if(currentNature==null){
      showToast("请选择事件性质");
      return;
    }
    var current = (detailData?.eventType.isNullOrEmpty()==true)?null:(currentNature.codeValueList??[]).firstWhere((e)=>e.codeValue==detailData?.eventType);
    DataPickerView(context, currentNature.codeValueList??[],currentFirstData: current,onSubmitListener: (p1,p2,p3){
      var item = (currentNature.codeValueList??[])[p1];
      detailData?.eventType = item.codeValue;
      detailData?.eventTypeName = item.name;
      notifyListeners();
    }).show();
  }

  void chooseStartTime(){
    var time = (detailData?.startDate??'').toDate();
    var format = ['yyyy','-','mm','-','dd'];
    DatePicker.showDatePicker(context,currentTime: time,onConfirm: (date){
      detailData?.startDate = "${date!.toDateStr(format)} 00:00:00";
      notifyListeners();
    });
  }

  void chooseOld(){
    Go().push(SelectOldPage((old){
      Go().pop();
      inEditMode = false;
      detailData?.name = old.name;
      detailData?.contact = old.preMobile?.replaceAll("手机:", "");
      detailData?.roomNo = old.roomNo;
      detailData?.roomId = old.roomId;
      notifyListeners();

      Future.delayed(Duration(milliseconds: 500),(){
        inEditMode = true;
        notifyListeners();
      });
    }));
  }

  void chooseComboInfo(
      {required String code,
        String? currentValue,
        double itemExtent = 40,
        required Function(CodeValueList value) onApply}) {
    var list = comboListMap[code] ?? [];
    var currentItem = currentValue == null
        ? null
        : list.firstWhere((element) => element.codeValue == currentValue);
    DataPickerView(context, list, currentFirstData: currentItem,
        onSubmitListener: (p1, p2, p3) {
          var item = list[p1];
          onApply(item);
        }, itemExtent: itemExtent)
        .show();
  }

  void chooseStaff() {
    Go().push(SelectEmployeePage(onSelectListener: (human){
      Go().pop();
      inEditMode = false;
      detailData?.name = human.name;
      detailData?.humanId = human.id?.toInt();
      detailData?.contact = human.mobile;
      notifyListeners();

      Future.delayed(Duration(milliseconds: 500),(){
        inEditMode = true;
        notifyListeners();
      });
    }));
  }

  Future<void> submitEvent(bool isSave) async {
    var submitInfo = detailData?.copyWith(isSave: isSave,status: 0,statusName: '草稿');
    var map = submitInfo!.toJson();
    map.removeWhere((key,value)=>value==null);
    showLoadingDialog(msg: '提交中...');
    try{
      await model.submitEvent(map);
      hideDialog();
      showToast('提交成功');
      finish(data: true);
    }catch(e){
      hideDialog();
      showToast(e.toNetError());
    }

  }

  void chooseImage(){
    showSelectCamera();
  }

  void showSelectCamera() {
    var items = ['拍摄', '相册'];
    showBottomSelect(context, items: items, onSelect: (str) async {
      if (str == "拍摄") {
        Permission.camera.checkRequestPermission(
          context,
          onSuccess: () async {
            var data = await ImagePicker().pickImage(source: ImageSource.camera);
            if(data!=null){
              upLoadImage(context, data.path, (model){
                (detailData?.attachList??=[])!.add(model);
                notifyListeners();
              });
            }
          },
          msg: "使用扫一扫扫描长者码、访客码等二维码以及拍照上传工作照片、长者头像、健康档案时，需要申请您的相机权限",
        );

      } else if (str == "相册") {
        var isAndroid13 = await isAndroid13OrAbove();
        if(isAndroid13){
          Permission.photos.checkRequestPermission(
            context,
            onSuccess: () async {
              var data = await ImagePicker().pickImage(source: ImageSource.gallery);
              if(data!=null){
                upLoadImage(context, data.path, (model){
                  (detailData?.attachList??=[])!.add(model);
                  notifyListeners();
                });
              }
            },
            msg: "从相册选取上传工作照片、长者头像、健康档案时，需要申请您的相册权限",
          );
        }else{
          Permission.storage.checkRequestPermission(
            context,
            onSuccess: () async {
              var data = await ImagePicker().pickImage(source: ImageSource.gallery);
              if(data!=null){
                upLoadImage(context, data.path, (model){
                  (detailData?.attachList??=[])!.add(model);
                  notifyListeners();
                });
              }
            },
            msg: "从相册选取上传工作照片、长者头像、健康档案时，需要申请您的相册权限",
          );
        }

      }
    });
  }
}